<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="章节名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入章节名称或课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属课程" prop="courseId">
        <el-select
          v-model="queryParams.courseId"
          placeholder="请选择所属课程"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="course in courseList"
            :key="course.id"
            :label="course.name"
            :value="course.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ssh:chapter:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ssh:chapter:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ssh:chapter:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleEnable"
          v-hasPermi="['ssh:chapter:edit']"
          >启用</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ssh:chapter:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="chapterList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="章节ID" align="center" prop="id" />
      <el-table-column label="章节名称" align="center" prop="name" />
      <el-table-column label="所属课程" align="center" prop="course.name" />
      <el-table-column label="状态" align="center" prop="del">
        <template slot-scope="scope">
          <el-tag :type="scope.row.del == '1' ? 'success' : 'danger'">
            {{ scope.row.del == "1" ? "正常" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ssh:chapter:edit']"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.del == '1'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ssh:chapter:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加章节对话框 -->
    <el-dialog
      title="添加章节"
      :visible.sync="addOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select
            v-model="addForm.courseId"
            placeholder="请选择所属课程"
            style="width: 100%"
          >
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改章节对话框 -->
    <el-dialog
      title="修改章节"
      :visible.sync="updateOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="updateForm"
        :model="updateForm"
        :rules="updateRules"
        label-width="80px"
      >
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="updateForm.name" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select
            v-model="updateForm.courseId"
            placeholder="请选择所属课程"
            style="width: 100%"
          >
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="del">
          <el-radio-group v-model="updateForm.del">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChapter,
  getChapter,
  delChapter,
  addChapter,
  updateChapter,
  enableChapter,
} from "@/api/ssh/chapter";
import { getAllCourse } from "@/api/ssh/course";

export default {
  name: "Chapter",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 章节表格数据
      chapterList: [],
      // 课程列表数据
      courseList: [],
      // 是否显示添加弹出层
      addOpen: false,
      // 是否显示修改弹出层
      updateOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseId: null,
        name: null,
      },
      // 添加表单参数
      addForm: {},
      // 修改表单参数
      updateForm: {},
      // 添加表单校验
      addRules: {
        courseId: [
          { required: true, message: "所属课程不能为空", trigger: "change" },
        ],
        name: [
          { required: true, message: "章节名称不能为空", trigger: "blur" },
        ],
      },
      // 修改表单校验
      updateRules: {
        courseId: [
          { required: true, message: "所属课程不能为空", trigger: "change" },
        ],
        name: [
          { required: true, message: "章节名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getCourseList();
  },
  methods: {
    /** 查询章节列表 */
    getList() {
      this.loading = true;
      listChapter(this.queryParams).then((response) => {
        this.chapterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取课程列表 */
    getCourseList() {
      getAllCourse().then((response) => {
        this.courseList = response.data;
      });
    },
    // 添加表单重置
    resetAddForm() {
      this.addForm = {
        courseId: null,
        name: null,
      };
      this.resetForm("addForm");
    },
    // 修改表单重置
    resetUpdateForm() {
      this.updateForm = {
        id: null,
        courseId: null,
        name: null,
        del: 1,
      };
      this.resetForm("updateForm");
    },
    /** 统一的提交方法 - 根据当前状态判断是新增还是修改 */
    submitForm() {
      // 判断当前是新增还是修改状态
      const isAdd = this.addOpen;
      const formRef = isAdd ? "addForm" : "updateForm";
      const formData = isAdd ? this.addForm : this.updateForm;
      const apiCall = isAdd ? addChapter : updateChapter;
      const successMsg = isAdd ? "新增成功" : "修改成功";

      this.$refs[formRef].validate((valid) => {
        if (valid) {
          apiCall(formData).then((response) => {
            this.$modal.msgSuccess(successMsg);
            // 关闭对应的对话框
            if (isAdd) {
              this.addOpen = false;
            } else {
              this.updateOpen = false;
            }
            this.getList();
          });
        }
      });
    },
    /** 统一的取消方法 - 根据当前状态判断关闭哪个对话框 */
    cancelForm() {
      // 判断当前是新增还是修改状态
      if (this.addOpen) {
        this.addOpen = false;
        this.resetAddForm();
      } else if (this.updateOpen) {
        this.updateOpen = false;
        this.resetUpdateForm();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetAddForm();
      this.addOpen = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetUpdateForm();
      const id = row.id || this.ids;
      getChapter(id).then((response) => {
        this.updateForm = response.data;
        this.updateOpen = true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除章节编号为"' + ids + '"的数据项？')
        .then(function () {
          return delChapter(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 启用按钮操作 */
    handleEnable() {
      const ids = this.ids;
      this.$modal
        .confirm('是否确认启用章节编号为"' + ids + '"的数据项？')
        .then(function () {
          return enableChapter(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("启用成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "ssh/chapter/export",
        {
          ...this.queryParams,
        },
        `chapter_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
